from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import datetime

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:123456@127.0.0.1:3306/f1"
# 如果设置成 True (默认情况)，Flask-SQLAlchemy 将会追踪对象的修改并且发送信号。
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

# 绑定app至SQLAlchemy
db = SQLAlchemy(app)


# 班级信息
class Classs(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    cname = db.Column(db.String(50))
    stus = db.relationship('Stus',backref='classs',cascade='all,delete,delete-orphan')
    # stus = db.relationship('Stus',backref="classs",cascade="all, delete,delete-orphan")
    def __repr__ (self):
        return '<Classs %r>'%self.cname


# 学生
class Stus(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    uname = db.Column(db.String(50))
    c_id = db.Column(db.Integer, db.ForeignKey('classs.id'))

    def __repr__ (self):
        return '<Stus %r>'% self.uname




if __name__ == "__main__":
   # 生成表
   # db.create_all()

   # 添加班级数据
   # c1 = Classs(cname='1')
   # c2 = Classs(cname='2')

   # db.session.add(c1)
   # db.session.add(c2)
   # db.session.commit()


   # 添加学生信息
   # me = Stus(
   #     uname = '田七',c_id='2'
   # )
   # db.session.add(me)
   # db.session.commit()

   # 获取所有学员班级信息
   # s = Stus.query.join(Classs).filter(Stus.c_id==Classs.id).all()
   # print(s[0].classs.cname)

   # s = db.session.query(Stus,classs).filter(Stus.c_id == Classs.id).all()
  # 通过学员查询班级
  # s = Stus.query.get(1)
  # print(s)
  # print(s.id)
  # print(s.uname)
  # print(s.cid)
  # print(s.classs.cname)


  # 通过班级查询学员
  c = Classs.query.get(1)
  print(c.stus)

  # 删除
  db.session.delete(c)
  db.session.commit()